package com.jwpdk.dbframework;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.jwpdk.common.Constant;

/**
 * 事务
 * @author 王志伟
 */
public class Transaction {
	private final Logger					log	= Logger.getLogger(this.getClass());
	private ConnectionManager	connectionManager;
	private Connection			connection		= null;
	private String				transactionName;
	private boolean				openB			= false;

	public Transaction() {
		this.transactionName = Constant.DEFAULT_CONNECTION;
	}

	public Transaction(String transactionName) {
		this.transactionName = transactionName;
	}

	public String getTransactionName() {
		return this.transactionName;
	}

	/**
	 * 事物是否开启
	 * @return
	 */
	public boolean isOpen() {
		return openB;
	}

	/** 开启事务 */
	void beginTransaction() throws Exception {
		try {
			openB = true;
			connectionManager = ConnectionManager.getInstance();
			if ( connectionManager.isNotExistsConnection(transactionName) ) {
				connection = connectionManager.getNewConnection();
				connectionManager.setConnectionPool(transactionName,connection);
			} else {
				connection = connectionManager.getConnection(transactionName);
			}
			connection.setAutoCommit(false);
		} catch ( Exception e ) {
			log.error(e);
			throw new Exception("开户事务时出现异常", e);
		}
	}

	/** 提交事务并关闭连接 */
	void endTransaction() throws Exception {
		try {
			connection = connectionManager.getConnection(transactionName);
			ConnectionManager.commitConnection(transactionName);
			ConnectionManager.closeConnection(transactionName);
			openB = false;
		} catch ( SQLException e ) {
			log.error(e);
			throw new Exception("提交事务时出现异常", e);
		}
	}

	/** 回滚并关闭连接 */
	void rollbackTransaction() throws Exception {
		try {
			connection = connectionManager.getConnection(transactionName);
			ConnectionManager.rollbackConnection(transactionName);
			ConnectionManager.closeConnection(transactionName);
			openB = false;
		} catch ( SQLException e ) {
			log.error(e);
			throw new Exception("回滚事务时出现异常", e);
		}
	}
}
